const { queryWords } = require("./wordDb");
const { extractKeywords } = require("./keywordExtractor");
const regularWordLemma = require("./regularWordLemma");

/**
 * 为字幕条目获取相关单词
 * @param {string} subtitleText - 字幕文本
 * @param {number} maxWords - 最大单词数
 * @returns {Promise<Array>} 单词信息数组
 */
async function getWordsForSubtitle(subtitleText, maxWords = -1) {
  try {
    if (maxWords <= 0) {
      maxWords = Math.floor(Math.random() * 2) + 5;
    }
    // 提取单词
    if(subtitleText === "") return [];    
    const words = extractKeywords(subtitleText, maxWords);
    if (words.length === 0) {
      return [];
    }
    
    let wordArr = words.split(" ");
    const newWords = [];
    wordArr.forEach(w => {
      const newW = regularWordLemma.getLemma(w);
      if (newW !== w) {
        newWords.push(newW);
      }
    });
    wordArr = wordArr.concat(newWords);
    wordArr.forEach((w, i) => {
      wordArr[i] = `\'${w}\'`;
    });
    // 查询单词，数据库中已经通过ORDER BY优先返回IELTS单词
    let wordInfos = await queryWords(wordArr, maxWords);
    // 限制返回数量
    return wordInfos.slice(0, maxWords);
  } catch (error) {
    console.error("！！！获取单词信息时出错:", error);
    return [];
  }
}

module.exports = {
  getWordsForSubtitle,
};
